// controller/admin.js
"use strict";
const Controller = require("egg").Controller;
const moment = require("moment");
class AdminController extends Controller {
  // 管理员登录
  async adminLogin() {
    const { ctx, app } = this;
    ctx.logger.info("管理员登录参数", ctx.request.body);
    const { username, password } = ctx.request.body;
    try {
      const userInfo = await ctx.service.admin.getAdminByName(username);
      ctx.logger.info("mysql结果", userInfo, Array.isArray(userInfo));
      if (userInfo.length == 0) {
        ctx.body = {
          code: 500,
          msg: "账号不存在",
          success: false,
          data: null,
        };
      } else {
        const index = userInfo.findIndex(function (item) {
          return item.password == password;
        });
        if (index == -1) {
          ctx.body = {
            code: 500,
            msg: "账号密码错误",
            success: false,
            data: null,
          };
        } else {
          // token 生成
          const token = app.jwt.sign(
            {
              id: userInfo[index].id,
              username: userInfo[index].username,
              exp: Math.floor(Date.now() / 1000) + 1 * 60 * 60, // token 有效期为 1 小时
            },
            app.config.jwt.secret
          );
          ctx.logger.info('admin-token 生成', token);
          ctx.body = {
            code: 200,
            message: "登录成功",
            success: true,
            data: {
              token,
            },
          };
        }
      }
    } catch (error) {
      console.log('error', error);
      ctx.status = 500;
      ctx.body = {
        msg: '获取管理员登录接口报错',
        success: false,
      }
    }
  }

  //获取管理员信息
  async getAdminInfo() {
    const { ctx, app } = this;
    const tokenResult = ctx.middlewareTokenResult
    ctx.logger.info('tokenResult', tokenResult);
    // 通过 token 携带的 username 获取到个人信息
    try {
      const userInfo = await ctx.service.admin.getAdminByName(tokenResult.username);
      // 默认头像
      const defaultAvatar = "https://profile.csdnimg.cn/4/2/E/3_weixin_38992765";
      ctx.body = {
        code: 200,
        msg: "请求成功",
        data: {
          id: userInfo.id,
          username: userInfo.username,
          signature: userInfo.signature || "",
          avatar: userInfo.avatar || defaultAvatar,
          nickname: userInfo.nickname || "不知名先生",
        }
      };
    } catch (error) {
      console.log('error', error);
      ctx.status = 500;
      ctx.body = {
        msg: '获取管理员信息接口报错',
        success: false,
      };
    }
  }

  // 注册（问题：现在没做安全控制，只需要传username和password就可以注册成功了）
  async register() {
    const { ctx } = this;
    const { username, password, nickname } = ctx.request.body;
    if (username && password) {
      const userInfo = await ctx.service.admin.getAdminByName(username);
      // 判断是否已经存在
      if (userInfo && userInfo.id) {
        ctx.body = {
          code: 500,
          msg: "账户名已被注册，请重新输入",
          data: null,
          success: false,
        };
      }
      const defaultAvatar = "https://profile.csdnimg.cn/4/2/E/3_weixin_38992765";
      let requestData = ctx.request.body;
      !requestData.permissions && (requestData.permissions = 0);
      !requestData.create_time && (requestData.create_time = moment().format("YYYY-MM-DD HH:mm:ss"));
      !requestData.signature && (requestData.signature = "暂无个人签名");
      !requestData.avatar && (requestData.avatar = defaultAvatar);
      const result = await ctx.service.admin.register(requestData);
      if (result) {
        ctx.body = {
          code: 200,
          msg: "注册成功",
          success: true,
        };
      } else {
        ctx.body = {
          code: 500,
          msg: "注册失败，请联系后台管理员",
          success: false,
        };
      }
    } else {
      ctx.body = {
        code: 500,
        msg: "信息错误，注册失败",
        success: false,
      };
    }
  }
}

module.exports = AdminController;
